<?php
/*
* 2007-2011 PrestaShop 
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2011 PrestaShop SA
*  @version  Release: $Revision: 8673 $
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

if (!defined('_PS_VERSION_'))
	exit;

class GroupBuyingReg extends Module
{
	private $_html = '';
	private $_postErrors = array();

	private $_group_buying_company;
	private $_coupon_codes;

	public function __construct()
	{
		$this->name = 'groupbuyingreg';
		$this->tab = 'Others';
		$this->version = '0.1';
		$this->author = 'EricLam';

		parent::__construct();

		$this->displayName = $this->l('Group buying registration');
		$this->description = $this->l('Customer to register and provide coupon codes from group buying companies');
		$this->confirmUninstall = $this->l('Are you sure you want to delete all group buying registrations?');
	}

	public function install()
	{
		if (!parent::install() OR
			!$this->registerHook('customerAccount') OR 
			!$this->registerHook('createAccountForm') OR 
			!$this->registerHook('createAccount')
		)
			return false;
    
    // create group_buying_registration table in DB
		if (!Db::getInstance()->Execute('
			CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'group_buying_registration` (
				`id_group_buying_registration` int unsigned NOT NULL AUTO_INCREMENT,
				`id_group_buying_company` int(2) unsigned NOT NULL,
				`id_group_buying_promotion` int(3) unsigned NOT NULL,
				`id_customer` int(10) unsigned NOT NULL,
				`coupon_codes` TEXT NOT NULL,
				`date_add` DATETIME NOT NULL,
				`date_upd` DATETIME NOT NULL,
				PRIMARY KEY  (`id_group_buying_registration`,`id_group_buying_company`,`id_customer`,`id_group_buying_promotion`)
			) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci') OR
			!Db::getInstance()->Execute('
			CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'group_buying_company_lang (
			`id_group_buying_company` int(2) NOT NULL,
			`id_lang` int(2) NOT NULL,
			`company_name` varchar(64) NOT NULL,
			`url_link` varchar(1000) NOT NULL,
			`active` int(1) NOT NULL,
			PRIMARY KEY(`id_group_buying_company`, `id_lang`))
			ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8 COLLATE=utf8_general_ci') OR
			!Db::getInstance()->Execute('
			CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'group_buying_promotion_lang (
			`id_group_buying_promotion` int(3) NOT NULL,
			`id_lang` int(2) NOT NULL,
			`id_group_buying_company` int(2) NOT NULL,
			`promotion_short_desc` varchar(256) NOT NULL,
			`promotion_desc` varchar(1000) NOT NULL,
			`url_link` varchar(1000) NOT NULL,
			`active` int(1) NOT NULL,
			PRIMARY KEY(`id_group_buying_promotion`, `id_lang`))
			ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8 COLLATE=utf8_general_ci')
		)
			return false;

		/* This hook is optional */
		$this->registerHook('myAccountBlock');
		return true;
	}

	public function uninstall()
	{
		if (!Db::getInstance()->Execute('DROP TABLE '._DB_PREFIX_.'group_buying_registration') OR 
		!Db::getInstance()->Execute('DROP TABLE '._DB_PREFIX_.'group_buying_company_lang') OR 
		!Db::getInstance()->Execute('DROP TABLE '._DB_PREFIX_.'group_buying_promotion_lang')
		)
			return false;
		return parent::uninstall();
	}
	
	public function hookCustomerAccount($params)
	{
		return $this->display(__FILE__, 'my-account.tpl');
	}
	
	public function hookMyAccountBlock($params)
	{
		return $this->hookCustomerAccount($params);
	}
	
	/**
	* Hook display on form create account
	* Add an additional input on bottom for filling in the group buying registration info
	*/
	public function hookCreateAccountForm($params)
	{
		include_once(dirname(__FILE__).'/GroupBuyingRegModule.php');

		global $smarty, $cookie;
		
		if (Tools::getValue('group_buying_company'))
			$selectedCompanies = (int)Tools::getValue('group_buying_company');
			
		if (Tools::getValue('group_buying_promotion'))
			$selectedPromotions = (int)Tools::getValue('group_buying_promotion');

		$smarty->assign(array(
			'group_buying_companies' => (GroupBuyingRegModule::getGroupBuyingCompanies((int)$cookie->id_lang)),
			'group_buying_promotions' => (GroupBuyingRegModule::getAllGroupBuyingPromotions((int)$cookie->id_lang)),
			'sl_company' => (isset($selectedCompanies) ? $selectedCompanies : '-'),
			'sl_promotion' => (isset($selectedPromotions) ? $selectedPromotions : '-')
		));
		
		return $this->display(__FILE__, 'authentication.tpl');
	}
	
	/**
	* Hook called on creation customer account
	* Register if group buying info filled
	*/
	public function hookCreateAccount($params)
	{
		global $cookie;
		
		$newCustomer = $params['newCustomer'];
		if (!Validate::isLoadedObject($newCustomer))
			return false;
			
		$postVars = $params['_POST'];
		if (empty($postVars) OR !isset($postVars['group_buying_company']) OR empty($postVars['group_buying_company'])
				OR !isset($postVars['group_buying_promotion']) OR empty($postVars['group_buying_promotion'])
				OR !isset($postVars['group_buying_coupon_code']) OR empty($postVars['group_buying_coupon_code'])
		)
			return false;
		
		$groupBuyingCompany = $postVars['group_buying_company'];
		$groupBuyingCompanyID = (int)Tools::getValue('group_buying_company');
		$groupBuyingPromotionID = (int)Tools::getValue('group_buying_promotion');
		$couponCodes = $postVars['group_buying_coupon_code'];
		
		include_once(dirname(__FILE__).'/GroupBuyingRegModule.php');
		
		if (!GroupBuyingRegModule::isValidPromotion($groupBuyingCompanyID, $groupBuyingPromotionID))
			return false;
		
		$reg = new GroupBuyingRegModule();
		$reg->id_customer = (int)$newCustomer->id;
		$reg->id_group_buying_company = (int)$groupBuyingCompanyID;
		$reg->id_group_buying_promotion = (int)$groupBuyingPromotionID;
		$reg->coupon_codes = $couponCodes;
		if (!$reg->validateFields(false))
			return false;
		else
			$reg->save();
			
		//$data = array('{firstname}' => $newCustomer->firstname, '{lastname}' => $newCustomer->lastname, '{group_buying_company}' => $groupBuyingCompany, '{coupon_codes}' => $couponCodes);
		//Mail::Send((int)$cookie->id_lang, 'registration_success', Mail::l('Congratulations!', (int)($cookie->id_lang)), $data, $newCustomer->email, $newCustomer->firstname.' '.$newCustomer->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__).'/mails/');
		
		return true;
	}


/***
	public static function deleteAlert($id_customer, $customer_email, $id_product, $id_product_attribute)
	{
		return Db::getInstance()->Execute('
			DELETE FROM `'._DB_PREFIX_.'mailalert_customer_oos` 
			WHERE `id_customer` = '.(int)($id_customer).'
			AND `customer_email` = \''.pSQL($customer_email).'\'
			AND `id_product` = '.(int)($id_product).'
			AND `id_product_attribute` = '.(int)($id_product_attribute));
	}

	public function hookDeleteCustomer($params)
	{
		Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'group_buying_registration` WHERE `id_customer` = '.(int)$params['customer']->id);
	}
***/
}
